<?php
declare (strict_types = 1);

namespace app\logic;

class FileLogic {

    public static function ins() {
        static $cls;
        if (!$cls) {
            $cls = new static();
        }
        return $cls;
    }

    /**
     * 获取 Execl 文件内容
     * @param string $file
     * @return array
     */
    public function getExeclCon($file) {
        try {
            // ini_set('memory_limit', '2048M'); // 设置为2GB
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            $reader->setReadDataOnly(true);
            $spreadsheet = $reader->load($file);
            $sheet = $spreadsheet->getActiveSheet();
            $data = $sheet->toArray();
        } catch (\Exception $e) {
            $data = [];
        }
        return $data;
    }

    /**
     * 下载 Execl 文件
     * @param array $data
     * @param string $filename
     * @param bool $isMulti 多表格
     */
    public function downExeclFile($data, $filename = 'down', $isMulti = false) {
        ob_clean();
        $spreadSheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        if ($isMulti) {
            $sheetNum = 0;
            foreach ($data as $list) {
                $sheetNum++;
                if ($sheetNum === 1) {
                    $sheet = $spreadSheet->getActiveSheet();
                } else {
                    $sheet = $spreadSheet->addSheet(new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadSheet, $list['title'] ?? ('Sheet ' . $sheetNum)));
                }
                $i = 0;
                foreach ($list['list'] as $key => $val) {
                    $i++;
                    $j = 0;
                    foreach ($val as $ke => $va) {
                        $j++;
                        $_v = $list['list'][$key][$ke] ?? null;
                        if ($_v !== '' && $_v !== null) {
                            if (is_string($_v) && strpos($_v, '=') === 0) {
                                $_v = ' ' . $_v;
                            }
                            // $sheet->setCellValueByColumnAndRow($j, $i, $_v);
                            $sheet->setCellValue([$j, $i], $_v);
                        }
                    }
                }
            }
        } else {
            $sheet = $spreadSheet->getActiveSheet();
            $i = 0;
            foreach ($data as $key => $val) {
                $i++;
                $j = 0;
                foreach ($val as $ke => $va) {
                    $j++;
                    $_v = $data[$key][$ke] ?? null;
                    if ($_v !== '' && $_v !== null) {
                        if (is_string($_v) && strpos($_v, '=') === 0) {
                            $_v = ' ' . $_v;
                        }
                        // $sheet->setCellValueByColumnAndRow($j, $i, $_v);
                        $sheet->setCellValue([$j, $i], $_v);
                    }
                }
            }
        }
        header('Cache-Control: no-store');
        header('Content-Type: application/octet-stream');
        header('Access-Control-Expose-Headers: Content-Disposition');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadSheet, 'Xlsx');
        $writer->save('php://output');
        exit();
    }

    /**
     * 运行数据所在文件夹
     * @param int $type
     * @return string
     */
    public function getRunFileDir($type = null) {
        $dev =env('APP_ENV');
        $local =  $dev === 'demo' ? '/var/www' : '';
        return $local.'/data/nas/数据清洗专用/' . env('DOMAIN_PREFIX') . 'RunFileData/';
    }

    /**
     * 清洗数据所在文件夹
     * @param int $type
     * @return string
     */
    public function getCleanFileDir($type=0) {
        $dev =env('APP_ENV');
        $local =  $dev === 'demo' && $type !==3 ? '' : '/';
        return '/data/nas/数据清洗专用/洋钱罐数据清洗目录';
    }

    public function getLocalCleanFileDir($type=0){
        return '/data/nas/洋钱罐数据清洗目录';
    }


    /**
     * 获取文件内容
     * @param $file
     * @return string|false
     */
    public function getFileContents($file) {
        try {
            return file_get_contents($file);
        } catch (\Throwable $e) {
            // lsyslog('file', 'get error: ' . $file);
        }
        return false;
    }

    /**
     * 保存文件内容
     * @param $file
     * @param $con
     * @return int|false
     */
    public function saveFileContents($file, $con) {
        try {
            return file_put_contents($file, $con);
        } catch (\Throwable $e) {
            // lsyslog('file', 'save error: ' . $file);
            // lerrlog('file', 'save', $e);
        }
        return false;
    }

    /**
     * 案件要素信息 存储JSON文件
     * @param int $type
     * @return string
     */
    public function getCasesDetailFile($type = null) {
        return $this->getRunFileDir($type) . request()->fhUuid . '/file_casesDetail.json';
    }
    
    /**
     * 保存清洗案件的相关要素信息
     * @param array $data
     * @return bool
     */
    public function saveCaseDetailData($data) 
    {
        if (empty($data)) {
            return false;
        }
        // if (!Lock::ins()->lock('handle:case:save:base:' . request()->fhUuid)) {
        //     return false;
        // }
        $runDir = $this->getRunFileDir() . request()->fhUuid;
        if (!is_dir($runDir)) {
            mkdir($runDir, 0777, true);
            echo $runDir;
        }
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        // dump($data);
        // echo $this->getCasesDetailFile();
        // exit();
        $result = FileLogic::ins()->saveFileContents($this->getCasesDetailFile(), $data);
        return $result;
    }

}